import re
import os
import argparse

def simple_format_novel(input_file, output_file):
    """简化版小说格式化函数"""
    
    with open(input_file, 'r', encoding='utf-8') as f:
        content = f.read()
    
    # 统一换行符
    content = content.replace('\r\n', '\n').replace('\r', '\n')
    
    # 分割成段落
    paragraphs = content.split('\n\n')
    formatted_paragraphs = []
    
    for para in paragraphs:
        if not para.strip():
            formatted_paragraphs.append('')
            continue
        
        # 合并段落内的错误换行
        lines = para.split('\n')
        merged_lines = []
        current_sentence = []
        
        for line in lines:
            line = line.strip()
            if not line:
                continue
            
            # 如果上一行以句子结束标点结尾，开始新段落
            if (current_sentence and 
                re.search(r'[。！？!?]', current_sentence[-1][-2:])):
                merged_lines.append(' '.join(current_sentence))
                current_sentence = [line]
            else:
                current_sentence.append(line)
        
        if current_sentence:
            merged_lines.append(' '.join(current_sentence))
        
        # 添加首行缩进
        formatted_para = '\n'.join(['    ' + line if i == 0 else line 
                                   for i, line in enumerate(merged_lines)])
        formatted_paragraphs.append(formatted_para)
    
    # 重新组合
    result = '\n\n'.join(formatted_paragraphs)
    
    with open(output_file, 'w', encoding='utf-8') as f:
        f.write(result)
    
    print(f"格式化完成！输出文件：{output_file}")

# 使用示例
if __name__ == "__main__":
    # 处理单个文件
    simple_format_novel("input.txt", "output.txt")
    
    # 或者批量处理文件夹
    # batch_process_folder("./novels/")